import { createRouter, createWebHistory } from "vue-router";
import Home from "@/views/Home.vue";
import Login from "@/views/Login.vue";
import Administrators from "@/views/Administrators.vue";
import Roles from "@/views/Roles.vue";
import Menus from "@/views/Menus.vue";
import Products from "@/views/Products.vue";
import Orders from "@/views/Orders.vue";
import OrderDetail from "@/views/OrderDetail.vue";
import RevenueList from "@/views/RevenueList.vue";
import ProductAttributes from "@/views/ProductAttributes.vue";
import ProductLabels from "@/views/ProductLabels.vue";
import ProductAdd from "@/views/ProductAdd.vue";
import ProductEdit from "@/views/ProductEdit.vue";
import ProductDetail from "@/views/ProductDetail.vue";
import PromotionList from "@/views/Promotions.vue";
import PromotionAdd from "@/views/PromotionAdd.vue";
import PromotionEdit from "@/views/PromotionEdit.vue";
import PromotionDetail from "@/views/PromotionDetail.vue";
import Banners from "@/views/Banners.vue";
import BannerAdd from "@/views/BannerAdd.vue";
import BannerEdit from "@/views/BannerEdit.vue";
import ImageCropperDemo from "@/views/ImageCropperDemo.vue";
import SystemConfig from "@/views/SystemConfig.vue";
import RevenueHome from "@/views/RevenueHome.vue";
import ProductCategory from "@/views/ProductCategory.vue";
import OrderRefund from "@/views/OrderRefund.vue";
import ScheduledTasks from "@/views/ScheduledTasks.vue";
import PaidRecords from "@/views/PaidRecords.vue";
import RefundRecords from "@/views/RefundRecords.vue";
import WithdrawalApply from "@/views/WithdrawalApply.vue";
import AddressManagement from "@/views/AddressManagement.vue";
import UserManagement from "@/views/UserManagement.vue";
import LeaderApply from "@/views/LeaderApply.vue";
import OrderShipping from "@/views/OrderShipping.vue";

const base = import.meta.env.MODE === "production" ? "/yfqy-web/" : "/";

const router = createRouter({
  history: createWebHistory(base),
  routes: [
    {
      path: "/",
      name: "Home",
      component: Home,
      meta: { requiresAuth: true },
    },
    {
      path: "/login",
      name: "Login",
      component: Login,
      meta: { requiresAuth: false },
    },
    {
      path: "/administrators",
      name: "Administrators",
      component: Administrators,
      meta: { requiresAuth: true },
    },
    {
      path: "/roles",
      name: "Roles",
      component: Roles,
      meta: { requiresAuth: true },
    },
    {
      path: "/menus",
      name: "Menus",
      component: Menus,
      meta: { requiresAuth: true },
    },
    {
      path: "/products",
      name: "Products",
      component: Products,
      meta: { requiresAuth: true },
    },
    {
      path: "/orders",
      name: "Orders",
      component: Orders,
      meta: { requiresAuth: true },
    },
    {
      path: "/order-detail/:id",
      name: "OrderDetail",
      component: OrderDetail,
      meta: { requiresAuth: true },
    },
    {
      path: "/revenue-list",
      name: "RevenueList",
      component: RevenueList,
      meta: { requiresAuth: true },
    },
    {
      path: "/product-attribute",
      name: "ProductAttributes",
      component: ProductAttributes,
      meta: { requiresAuth: true },
    },
    {
      path: "/product-labels",
      name: "ProductLabels",
      component: ProductLabels,
      meta: { requiresAuth: true },
    },
    {
      path: "/product/add",
      name: "ProductAdd",
      component: ProductAdd,
      meta: { requiresAuth: true },
    },
    {
      path: "/product/edit/:productId",
      name: "ProductEdit",
      component: ProductEdit,
      meta: { requiresAuth: true },
    },
    {
      path: "/product/detail/:productId",
      name: "ProductDetail",
      component: ProductDetail,
      meta: { requiresAuth: true },
    },
    {
      path: "/promotions",
      name: "PromotionList",
      component: PromotionList,
      meta: { requiresAuth: true },
    },
    {
      path: "/promotion-add",
      name: "PromotionAdd",
      component: PromotionAdd,
      meta: { requiresAuth: true },
    },
    {
      path: "/promotion-edit/:id",
      name: "PromotionEdit",
      component: PromotionEdit,
      meta: { requiresAuth: true },
    },
    {
      path: "/promotion-detail/:id",
      name: "PromotionDetail",
      component: PromotionDetail,
      meta: { requiresAuth: true },
    },
    {
      path: "/banners",
      name: "Banners",
      component: Banners,
      meta: { requiresAuth: true },
    },
    {
      path: "/banner-add",
      name: "BannerAdd",
      component: BannerAdd,
      meta: { requiresAuth: true },
    },
    {
      path: "/banner-edit/:id",
      name: "BannerEdit",
      component: BannerEdit,
      meta: { requiresAuth: true },
    },
    {
      path: "/image-cropper-demo",
      name: "ImageCropperDemo",
      component: ImageCropperDemo,
      meta: { requiresAuth: true },
    },
    {
      path: "/system-config",
      name: "SystemConfig",
      component: SystemConfig,
      meta: { requiresAuth: true },
    },
    {
      path: "/revenue-home",
      name: "RevenueHome",
      component: RevenueHome,
      meta: { requiresAuth: true },
    },
    {
      path: "/product-category",
      name: "ProductCategory",
      component: ProductCategory,
      meta: { requiresAuth: true },
    },
    {
      path: "/order-refund",
      name: "OrderRefund",
      component: OrderRefund,
      meta: { requiresAuth: true },
    },
    {
      path: "/scheduled-tasks",
      name: "ScheduledTasks",
      component: ScheduledTasks,
      meta: { requiresAuth: true },
    },
    {
      path: "/pay-records",
      name: "PaidRecords",
      component: PaidRecords,
      meta: { requiresAuth: true },
    },
    {
      path: "/refund-records",
      name: "RefundRecords",
      component: RefundRecords,
      meta: { requiresAuth: true },
    },
    {
      path: "/withdrawal-apply",
      name: "WithdrawalApply",
      component: WithdrawalApply,
      meta: { requiresAuth: true },
    },
    {
      path: "/address",
      name: "AddressManagement",
      component: AddressManagement,
      meta: { requiresAuth: true },
    },
    {
      path: "/userManagement",
      name: "UserManagement",
      component: UserManagement,
      meta: { requiresAuth: true },
    },
    {
      path: "/leaderApply",
      name: "LeaderApply",
      component: LeaderApply,
      meta: { requiresAuth: true },
    },
    {
      path: "/order-shipping",
      name: "OrderShipping",
      component: OrderShipping,
      meta: { requiresAuth: true },
    },
  ],
});

router.beforeEach((to, _from, next) => {
  const token = localStorage.getItem("token");
  const isLoggedIn = !!token;
  const requiresAuth = to.meta.requiresAuth !== false;

  console.log("路由守卫检查:", {
    to: to.path,
    requiresAuth,
    isLoggedIn,
    token: token ? "存在" : "不存在",
  });

  if (requiresAuth && !isLoggedIn) {
    // 记录当前路径，登录后跳转回来
    console.log("需要登录，记录路径:", to.fullPath);
    localStorage.setItem("lastVisitedPath", to.fullPath);
    next("/login");
  } else if (to.path === "/login" && isLoggedIn) {
    // 已登录用户访问登录页，跳转到首页或记录的最后访问路径
    const lastVisitedPath = localStorage.getItem("lastVisitedPath");
    console.log("已登录用户访问登录页，跳转到:", lastVisitedPath || "/");
    next(lastVisitedPath || "/");
  } else if (requiresAuth && isLoggedIn) {
    // 检查token是否有效（简单检查token格式）
    if (token && token.length > 10) {
      console.log("token有效，正常跳转到:", to.path);
      next();
    } else {
      console.log("token无效，清除token并跳转到登录页");
      localStorage.removeItem("token");
      localStorage.setItem("lastVisitedPath", to.fullPath);
      next("/login");
    }
  } else {
    console.log("正常跳转到:", to.path);
    next();
  }
});

export default router;
